package com.gewu.pm.ui.adapter;

import android.content.Context;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.gewu.pm.R;
import com.gewu.pm.app.AppAdapter;
import com.hjq.base.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 筛选页面 - 通用标签适配器（多选）
 */
public final class FilterMultiTagAdapter extends AppAdapter<String> {

    /** 选中的位置列表 */
    private final List<Integer> mSelectedPositions = new ArrayList<>();

    public FilterMultiTagAdapter(Context context) {
        super(context);
    }

    @NonNull
    @Override
    public BaseAdapter<?>.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder();
    }

    private final class ViewHolder extends AppAdapter<?>.ViewHolder {

        private final TextView mTvTag;

        private ViewHolder() {
            super(R.layout.filter_time_item);
            mTvTag = findViewById(R.id.tv_time);
        }

        @Override
        public void onBindView(int position) {
            String tagText = getItem(position);
            mTvTag.setText(tagText);
            
            // 设置选中状态
            mTvTag.setSelected(mSelectedPositions.contains(position));
        }
    }

    /**
     * 切换选中状态
     * 
     * @param position 要切换的位置
     */
    public void toggleSelection(int position) {
        if (mSelectedPositions.contains(position)) {
            mSelectedPositions.remove(Integer.valueOf(position));
        } else {
            mSelectedPositions.add(position);
        }
        notifyItemChanged(position);
    }

    /**
     * 获取选中的位置列表
     */
    public List<Integer> getSelectedPositions() {
        return new ArrayList<>(mSelectedPositions);
    }

    /**
     * 获取选中的文字列表
     */
    public List<String> getSelectedTexts() {
        List<String> texts = new ArrayList<>();
        for (int position : mSelectedPositions) {
            if (position >= 0 && position < getCount()) {
                texts.add(getItem(position));
            }
        }
        return texts;
    }

    /**
     * 获取选中的文字（逗号分隔）
     */
    public String getSelectedText() {
        List<String> texts = getSelectedTexts();
        if (texts.isEmpty()) {
            return "";
        }
        return String.join(",", texts);
    }

    /**
     * 清除选中状态
     */
    public void clearSelection() {
        List<Integer> oldPositions = new ArrayList<>(mSelectedPositions);
        mSelectedPositions.clear();
        for (int position : oldPositions) {
            if (position >= 0 && position < getCount()) {
                notifyItemChanged(position);
            }
        }
    }
}
